package com.hinnotek.amoeba.ui.activity.old

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.PTProjectAdapter
import com.hinnotek.amoeba.bean.old.PtCustomerProjectBean
import com.hinnotek.amoeba.databinding.IncludeRecyclerviewRefreshBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.utilities.IntentUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.viewmodels.AmibaCustomerViewModel
import com.lee.common.network.net.ObserverState
import com.scwang.smart.refresh.layout.api.RefreshLayout
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class PTProjectListActivity : BaseActivity<IncludeRecyclerviewRefreshBinding>() {

    private var pageNo = 1
    private val pageSize = 20
    private var customerId = 0
    private var customDialog: CustomDialog? = null
    private var titleUser: String? = null

    private var mAdapter: PTProjectAdapter? = null

    private val viewModel by viewModels<AmibaCustomerViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.include_recyclerview_refresh)
        setLeftVisible(true)
        titleUser = intent.getStringExtra("title")
        setTitle(titleUser)

        setRightText("创建项目")?.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt("customerId", customerId)
            IntentUtils.startActivityForResult(
                this@PTProjectListActivity,
                PTCreateProjectActivity::class.java,
                bundle,
                1
            )
        }
    }

    override fun initVew() {
        val manager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
        bindingView.recyclerView.layoutManager = manager
        bindingView.recyclerView.adapter = PTProjectAdapter().also { mAdapter = it }
        mAdapter?.setOnItemClickListener { adapter1: BaseQuickAdapter<*, *>, _: View?, position: Int ->
            val customerProject= adapter1.getItem(position) as PtCustomerProjectBean
            val bundle = Bundle()
            bundle.putString("title", titleUser)
            bundle.putInt("amibaCustomerProjectId", customerProject.amibaCustomerProjectId)
            IntentUtils.startActivity(mContext, PTProjectDetailActivity::class.java, bundle)
        }
        customDialog = CustomDialog(mContext, "正在加载...")
        customDialog?.show()
    }

    override fun setData() {
        customerId = intent.getIntExtra("customerId", 0)
        //下拉刷新
        bindingView.refreshLayout.setOnRefreshListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo = 1
                    getAmoebaCustomer()
                }, 500
            )
        }
        //上拉加载
        bindingView.refreshLayout.setOnLoadMoreListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo++
                    getAmoebaCustomer()
                }, 0
            )
        }
        bindingView.refreshLayout.autoRefresh() //第一次进入触发自动刷新，演示效果
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 1) {
            bindingView.refreshLayout.autoRefresh()
        }
        super.onActivityResult(requestCode, resultCode, data)
    }//将不会再次触发加载更多事件//setNoMoreData(false);

    /**
     * app端查询阿米巴某个客户下的所有项目接口
     */
    private fun getAmoebaCustomer(){

        viewModel.getProjectPageByCustomerId(customerId,pageNo,pageSize).observe(this,object:ObserverState<MutableList<PtCustomerProjectBean>>(){
            override fun onDataChange(data: MutableList<PtCustomerProjectBean>) {
                super.onDataChange(data)

                customDialog?.dismiss()
                if (pageNo == 1) {
                    when (getRefreshStatus(data.size)) {
                        Status.SUCCESS -> {
                            mAdapter?.setList(data)
                            if (data.size < pageSize) {
                                bindingView.refreshLayout.setEnableLoadMore(false)
                            } else {
                                bindingView.refreshLayout.setEnableLoadMore(true)
                            }
                            bindingView.refreshLayout.resetNoMoreData() //setNoMoreData(false);
                            bindingView.llStateful.showContent()
                        }
                        Status.EMPTY -> {
                            bindingView.llStateful.showEmpty()
                            bindingView.refreshLayout.setEnableLoadMore(false)
                        }
                        Status.ERROR -> showError()
                        Status.NO_NET -> showOffline()
                    }
                    bindingView.refreshLayout.finishRefresh()
                } else {
                    if (data.size == 0) {
                        ToastUtils.showShort("数据全部加载完毕")
                        bindingView.refreshLayout.finishLoadMoreWithNoMoreData() //将不会再次触发加载更多事件
                    } else {
                        mAdapter?.addData(data.toMutableList())
                        bindingView.refreshLayout.finishLoadMore()
                    }
                }

            }

            override fun onError(msg: String?, code: Int) {
                ToastUtils.showShort(mContext, msg)
                customDialog?.dismiss()
                super.onError(msg, code)
            }
        })

    }

    private fun showOffline() {
        bindingView.llStateful.showOffline { bindingView.refreshLayout.autoRefresh() }
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private fun showError() {
        bindingView.llStateful.showError { bindingView.refreshLayout.autoRefresh() }
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private enum class Status {
        SUCCESS, EMPTY, ERROR, NO_NET
    }

    private fun getRefreshStatus(size: Int): Status {
        return  if (size == 0) {
            Status.EMPTY
        } else Status.SUCCESS
    }
}